<template>
    <div class="app-container">
      <div class="container_box">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="14" :xl="12">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
              <el-row>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="發票編碼" prop="invoiceCode">
                    <el-input
                    disabled
                      v-model="form.invoiceCode"
                      placeholder="請輸入發票編碼"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="標題" prop="invoiceTitle">
                    <el-input
                      v-model="form.invoiceTitle"
                      placeholder="請輸入標題"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="報價單編碼" prop="quoteCode">
                    <el-input
                      disabled
                      v-model="form.quoteCode"
                      placeholder="請選擇報價單"
                    >
                      <el-button
                        slot="append"
                        @click="open_dialog_customer"
                        icon="el-icon-search"
                      ></el-button>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                    <el-form-item label="客戶id" prop="customerId">
                      <el-input
                        v-model="form.customerId"
                        placeholder="請輸入客戶id"
                      />
                    </el-form-item>
                  </el-col> -->
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="客戶編碼" prop="customerCode">
                    <el-input
                      disabled
                      v-model="form.customerCode"
                      placeholder="請輸入客戶編碼"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="客戶名稱" prop="customerName">
                    <el-input
                      disabled
                      v-model="form.customerName"
                      placeholder="請輸入客戶名稱"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
          
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="入賬銀行賬號" prop="inBankNo">
                    <el-input
                      disabled
                      v-model="form.inBankNo"
                      placeholder="請輸入入賬銀行賬號"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="入賬銀行名稱" prop="inBankName">
                    <el-input
                      disabled
                      v-model="form.inBankName"
                      placeholder="請輸入入賬銀行名稱"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="入賬賬戶" prop="inBankAmount">
                    <el-input
                      disabled
                      v-model="form.inBankAmount"
                      placeholder="請輸入入賬賬戶"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="有效天數" prop="validDays">
                    <el-input
                      v-model="form.validDays"
                      placeholder="請輸入有效天數"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
               
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="開票時間" prop="invoiceTime">
                    <el-date-picker
                      clearable
                      v-model="form.invoiceTime"
                      type="datetime"
                      style="width: 100%"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="請選開票時間"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="稅率" prop="taxRate">
                    <el-input
                      maxlength="4"
                      placeholder="請輸入稅率（0-1）"
                      @change="taxRate_change"
                      oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
                      v-model="form.taxRate"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="備註" prop="remark">
                    <el-input v-model="form.remark" placeholder="請輸入備註" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-divider content-position="center">發票明細信息</el-divider>
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAddBizInvoiceItem"
                    >添加</el-button
                  >
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="handleDeleteBizInvoiceItem"
                    >删除</el-button
                  >
                </el-col>
              </el-row>
              <el-table
                style="width: 100%"
                :data="bizInvoiceItemList"
                :row-class-name="rowItemIndex"
                :row-key="
                  (row) => {
                    return row.index;
                  }
                "
                @selection-change="SelectionChange"
                ref="bizCustomerReservationItem"
              >
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column
                  label="序號"
                  align="center"
                  prop="index"
                  width="50"
                />
                <el-table-column label="發票事項" prop="invoiceItem" width="150">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.invoiceItem"
                      placeholder="請選擇預約事項"
                      clearable
                    >
                      <el-option
                        v-for="dict in dict.type.business_scope"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  label="發票金額"
                  align="center"
                  prop="itemAmount"
                >
                  <template slot-scope="scope">
                    <el-input
                      min="0"
                      @change="amountSum(scope.row)"
                      v-model="scope.row.itemAmount"
                      placeholder="請輸入發金額"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="備註" prop="remark">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.remark"
                      placeholder="請輸入備註"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="稅金" align="center" prop="taxAmount">
                  <template slot-scope="scope">
                    <span v-if="scope.row.itemAmount">{{
                      scope.row.taxAmount
                    }}</span>
                    <span v-else>0</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="發票含稅金額"
                  align="center"
                  prop="itemTaxAmount"
                >
                  <template slot-scope="scope">
                    <span v-if="scope.row.itemAmount">{{
                      scope.row.itemTaxAmount
                    }}</span>
                    <span v-else>0</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <div style="text-align: center; margin-top: 16px">
              <el-button type="primary" @click="submitForm('20')"
                >提 交</el-button
              >
              <el-button type="primary" @click="submitForm('10')"
                >保 存</el-button
              >
              <el-button @click="cancel">取 消</el-button>
            </div>
          </el-col>
        </el-row>
  
        <!-- 選擇報價單 -->
        <el-dialog
          v-if="dialog_if_customer"
          :visible.sync="open_customer"
          destroy-on-close
          :close-on-click-modal="false"
          width="600px"
          append-to-body
        >
          <!-- 单选表格 -->
          <el-table
            v-loading="loading"
            :data="userList_customer"
            class="signType"
            max-height="500"
            ref="multipleTable_customer"
            @selection-change="handleSelectionChange_customer"
            @select="selectTable_customer"
            :row-key="
              (row) => {
                return row.id;
              }
            "
          >
            <el-table-column
              type="selection"
              width="50"
              align="center"
              :reserve-selection="true"
            />
            <el-table-column label="報價編碼" align="center" prop="quoteCode">
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="標題"
              align="center"
              prop="quoteTitle"
            />
            <el-table-column
              show-overflow-tooltip
              label="報價時間"
              align="center"
              prop="quoteTime"
            >
              <template slot-scope="scope">
                <span>{{
                  parseTime(scope.row.quoteTime, "{y}-{m}-{d} {h}:{i}:{s}")
                }}</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="cancel_customer_customer">取 消</el-button>
            <el-button type="primary" @click="choose_customer_customer"
              >確 定</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </template>
      
      <script>
  import {
    listCustomer,
    getCustomer,
    delCustomer,
    addCustomer,
    updateCustomer,
  } from "@/api/biz/customer";
  import {
    listInvoice,
    getInvoice,
    delInvoice,
    addInvoice,
    updateInvoice,
  } from "@/api/biz/invoice";
  import {
    listQuote,
    getQuote,
    delQuote,
    addQuote,
    updateQuote,
  } from "@/api/biz/quote";
  export default {
    name: "InvoiceEdit",
    dicts: [
      "customer_type",
      "customer_tag",
      "customer_source",
      "industry_type",
      "cart_type",
      "sys_user_sex",
      "customer_level",
      "business_scope",
    ],
    data() {
      return {
        // 表单參數
        form: {
          validDays: 30,
          taxRate: 0,
        },
        // 表单校验
        rules: {},
        // 發票明細表格數据
        bizInvoiceItemList: [],
        checkedList: [],
        //------------------------
        open_customer: false,
        dialog_if_customer: false,
        multipleSelection_customer: [],
        select_customer_customer: {},
        userList_customer: [],
      };
    },
    created() {
      if (this.$route.query.id) {
        console.log(this.$route.query);
        this.get_detail(this.$route.query.id);
      }
    },
    activated() {
      if (this.$route.query.id) {
        console.log(this.$route.query);
        this.get_detail(this.$route.query.id);
      }
    },
    methods: {
      get_detail(id) {
        getInvoice(id).then((response) => {
          this.form = response.data;
          this.bizInvoiceItemList = response.data.bizInvoiceItemList;
        });
      },
      /** 提交按钮 */
      submitForm(type) {
        console.log(this.bizInvoiceItemList);
        this.form.taxAmount = 0; //稅金
        this.form.invoiceAmount = 0; //報價金額
        this.form.invoiceTaxAmount = 0; // 含稅報價
        this.bizInvoiceItemList.map((item) => {
          item.unitPrice = item.itemAmount;
          this.form.invoiceAmount += item.itemAmount - 0;
          this.form.taxAmount += item.taxAmount - 0;
          this.form.invoiceTaxAmount += item.itemTaxAmount - 0;
        });
        // (scope.row.itemAmount * form.taxRate).toFixed(2)
        this.form.bizInvoiceItemList = this.bizInvoiceItemList;
        this.form.invoiceStatus = type;
        this.$refs["form"].validate((valid) => {
          if (valid) {
              updateInvoice(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.$tab.closePage().then(() => {
                // 执行結束的逻辑
                const obj = { path: "/invoice/invoice", name: "Invoice" };
                this.$tab.refreshPage(obj);
              });
            });
          }
        });
      },
      cancel() {
        this.$tab.closePage().then(() => {
          // 执行結束的逻辑
          const obj = { path: "/invoice/invoice", name: "Invoice" };
          this.$tab.refreshPage(obj);
        });
      },
  
      /** 复选框选中數据 */
      SelectionChange(selection) {
        this.checkedList = selection.map((item) => item.index);
      },
      /** 發票明細序號 */
      rowItemIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
      },
      /** 發票明細添加按钮操作 */
      handleAddBizInvoiceItem() {
        let obj = {};
        obj.invoiceItem = "";
        obj.itemAmount = "";
        obj.taxAmount = "";
        obj.itemTaxAmount = "";
        obj.tax = this.form.taxRate;
        obj.quantity = 1;
        obj.uint = "個";
        obj.unitPrice = "";
        obj.remark = "";
        this.bizInvoiceItemList.push(obj);
      },
      /** 發票明細删除按钮操作 */
      handleDeleteBizInvoiceItem() {
        if (this.checkedList.length == 0) {
          this.$modal.msgError("請先選擇要删除的發票明細數据");
        } else {
          const bizInvoiceItemList = this.bizInvoiceItemList;
          const checkedList = this.checkedList;
          this.bizInvoiceItemList = bizInvoiceItemList.filter(function (item) {
            return checkedList.indexOf(item.index) == -1;
          });
        }
      },
      // 計算金額
      amountSum(item) {
        this.bizInvoiceItemList[item.index - 1].tax = this.form.taxRate;
        this.bizInvoiceItemList[item.index - 1].taxAmount = this.computeTaxAmount(
          this.bizInvoiceItemList[item.index - 1].itemAmount,
          this.form.taxRate
        );
        this.bizInvoiceItemList[item.index - 1].itemTaxAmount =
          this.computeItemTaxAmount(
            this.bizInvoiceItemList[item.index - 1].itemAmount,
            this.form.taxRate
          );
        this.$forceUpdate();
        this.bizInvoiceItemList.splice(1, 0);
        console.log(this.bizInvoiceItemList);
      },
      computeTaxAmount(itemAmount, taxRate) {
        return (itemAmount * taxRate).toFixed(2);
      },
      computeItemTaxAmount(itemAmount, taxRate) {
        return (itemAmount * (1 + (taxRate - 0))).toFixed(2);
      },
      // 稅率變化
      taxRate_change() {
        this.bizInvoiceItemList.map((item) => {
          item.tax = this.form.taxRate;
          item.taxAmount = this.computeTaxAmount(
            item.itemAmount,
            this.form.taxRate
          );
          item.itemTaxAmount = this.computeItemTaxAmount(
            item.itemAmount,
            this.form.taxRate
          );
        });
        console.log(this.bizInvoiceItemList);
        this.$forceUpdate();
        this.bizInvoiceItemList.splice(1, 0);
      },
  
      // 選擇報價單
      open_dialog_customer() {
        this.open_customer = true;
        this.dialog_if_customer = true;
        this.getList_customer();
      },
      getList_customer() {
        // 根据实际需求，调用对应接口...........
        this.loading = true;
        listQuote({
          pageNum: 1,
          pageSize: 9999,
          open: false,
          orderByColumn: "update_time",
        })
          .then((res) => {
            this.userList_customer = res.rows;
            this.total = res.total;
            this.loading = false;
            //   數据回显
            let that = this;
            this.$nextTick(() => {
              console.log(this.multipleSelection_customer);
              if (this.form.customerCode && this.form.customerCode != "") {
                this.userList_customer.forEach((row) => {
                  if (row.id == this.select_customer_customer.id) {
                    that.$refs.multipleTable_customer.toggleRowSelection(row);
                  }
                });
              } else {
                that.$refs.multipleTable_customer.clearSelection();
              }
            });
          })
          .catch((err) => {
            console.log(err);
            this.loading = false;
          });
      },
      choose_customer_customer() {
        console.log(1111);
        console.log(this.multipleSelection_customer);
        this.select_customer_customer = this.multipleSelection_customer[0];
  
        this.form.customerCode = this.multipleSelection_customer[0].customerCode;
        this.form.customerId = this.multipleSelection_customer[0].customerId;
        this.form.customerName = this.multipleSelection_customer[0].customerName;
  
        this.form.quoteId = this.multipleSelection_customer[0].id;
        this.form.quoteCode = this.multipleSelection_customer[0].quoteCode;
        this.form.inBankId = this.multipleSelection_customer[0].inBankId;
        this.form.inBankNo = this.multipleSelection_customer[0].inBankNo;
        this.form.inBankName = this.multipleSelection_customer[0].inBankName;
        this.form.inBankAmount = this.multipleSelection_customer[0].inBankAccount;
        this.$refs.multipleTable_customer.clearSelection();
        this.open_customer = false;
        this.dialog_if_customer = false;
      },
      cancel_customer_customer() {
        this.$refs.multipleTable_customer.clearSelection();
        this.open_customer = false;
      },
      handleSelectionChange_customer(val) {
        if (val.length > 1) {
          this.$refs.multipleTable_customer.clearSelection();
          this.$refs.multipleTable_customer.toggleRowSelection(val.pop());
        }
      },
      selectTable_customer(selection, row) {
        this.multipleSelection_customer = [row];
      },
    },
  };
  </script>
    <style  >
  .signType thead .el-table-column--selection .cell {
    display: none;
  }
  .dialog-footer {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  </style>
      